package com.tanhua.admin.service;

import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.admin.exception.BusinessException;
import com.tanhua.admin.interceptor.AdminHolder;
import com.tanhua.admin.mapper.AdminMapper;
import com.tanhua.commons.utils.Constants;
import com.tanhua.commons.utils.JwtUtils;
import com.tanhua.model.domain.Admin;
import com.tanhua.model.vo.AdminVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class AdminService {

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;


    // 用户登录
    public Map login(Map map) {
        // 1:获取请求参数
        String username = (String) map.get("username");
        String password = (String) map.get("password");
        String verificationCode = (String) map.get("verificationCode");
        String uuid = (String) map.get("uuid");
        // 2:校验验证码是否正确
        String key = Constants.CAP_CODE + uuid;
        String code = redisTemplate.opsForValue().get(key);
        if (StringUtils.isEmpty(code) || !code.equals(verificationCode)){
            throw  new BusinessException("验证码错误");
        }
        // 3:根据用户名查询管理员对象,Admin;
        QueryWrapper<Admin> qw = new QueryWrapper<Admin>().eq("username",username);
        Admin admin = adminMapper.selectOne(qw);
        // 4:判断管理员对象是否存在,密码是否一致
        password = SecureUtil.md5(password); //md5加密
        if (admin == null || !password.equals(admin.getPassword())){
            throw new BusinessException("用户名或者密码错误");
        }
        // 5:生成token
        Map<String,Object> claims = new HashMap<>();
        claims.put("username",username);
        claims.put("id",admin.getId());
        String token = JwtUtils.getToken(claims);
        // 6:构造返回值
        Map retMap = new HashMap();
        retMap.put("token",token);
        return retMap;
    }


    // 获取用户的信息
    public AdminVo profile() {
        Long id = AdminHolder.getUserId();
        Admin admin = adminMapper.selectById(id);
        return AdminVo.init(admin);
    }

    // 退出登录
    public void logout() {

    }
}
